<template>
  <div>
    <!-- 选择 -->
    <el-select
      v-model="selected"
      placeholder="请选择"
      :readonly="readonly"
      :filterable="true"
      @change="onSelectChanged"
    >
      <el-option
        v-for="opt in options"
        :key="opt.value"
        :label="opt.name"
        :value="opt.value"
      />
    </el-select>
    <slot />
  </div>
</template>

<script>
import { getList, getMainName } from './apidefines'
import { sortByName } from '@/utils'
export default {
  name: 'FromApi',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    readonly: {
      type: Boolean,
      default: false
    },
    apiname: {
      type: String,
      default: function() {
        return ''
      }
    },
    value: {
      type: [Number, Object, String],
      default: function() {
        return {}
      }
    },
    query: {
      type: Object,
      default: function() {
        return {
          query: '',
          queryColumn: '',
          order: '',
          column: '',
          curPage: 1,
          pageSize: 200
        }
      }
    }
  },
  data() {
    return {
      selected: this.value,
      form: {},
      options: [],
      listQuery: {
        query: '',
        queryColumn: '',
        order: '',
        column: '',
        curPage: 1,
        pageSize: 200
      },
      listData: {
        current: 0,
        pages: 0,
        searchCount: true,
        size: 20,
        total: 0,
        records: []
      }
    }
  },
  computed: {
    itemid() {
      return this.$route.params.id
    },
    cname() {
      return this.$route.params.cname
    }
  },
  watch: {
    apiname(newValues) {
      this.$nextTick(() => {
        this.fetchData()
      })
    },
    value(newValues) {
      this.selected = newValues
    },
    query(newValues) {
      this.listQuery = newValues
    }
  },
  mounted() {
    this.listQuery = this.query
    this.fetchData()
    // this.$nextTick(() => {
    // })
  },
  methods: {
    fetchData() {
      getList(this.apiname, this.listQuery).then(ret => {
        // console.log(999, this.apiname, ret)
        this.listData = ret.data
        if (ret.data.records) {
          this.options = sortByName(ret.data.records.map((val) => {
            return { name: getMainName(this.apiname, val), value: val.id }
          }))
        }
      })
    },
    onSelectChanged(event) {
      console.log('selected', this.selected, event)
      this.$emit('change', this.selected)
    }
  }
}
</script>

<style scoped>
.line{
  text-align: center;
}
</style>

